package com.cms.server.resolver.plugins;

import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Date;

import com.efounder.builder.base.data.DataSetUtils;
import com.efounder.builder.base.data.EFDataSet;
import com.efounder.builder.base.data.EFRowSet;
import com.efounder.eai.data.JParamObject;
import com.efounder.form.EFFormDataModel;
import com.efounder.form.io.FormDataResolverAdapter;
import com.efounder.form.server.resolver.util.SYS_MDL_VAL;
import com.efounder.sql.JStatement;
import com.metadata.bizmodel.SYS_MODEL;
import com.persistence.FLOW_TASK_LIST;

public class CMSRollbackManagerApprovalPSHTForm extends FormDataResolverAdapter {

	//初始化FormDataModel
	public void saveBillData(JStatement stmt, EFFormDataModel model, JParamObject PO) throws Exception {
		EFDataSet                    billDataSet = model.getBillDataSet();
		EFDataSet                      BMDataset = EFDataSet.getInstance(new String[]{"F_BMBH"});
		EFDataSet                    flowDataset = EFDataSet.getInstance(new String[]{"OP_BMBH"});
		EFDataSet                 endFlowDataset = EFDataSet.getInstance(new String[]{"OP_BMBH"});
		EFDataSet                 QRFlowDataset = EFDataSet.getInstance(new String[]{"TASK_TO_UNIT"});
		EFRowSet                      itemRowSet;
		EFRowSet              nextFlowNodeRowSet = null;
		EFRowSet               preFlowNodeRowSet = null;
		EFRowSet                      flowRowSet = null;
		EFRowSet                        BMRowSet = null;
		EFDataSet                    itemDataSet;
		String                            strSql = "";
		ResultSet                             rs = null;
		long                             curTime = new Date().getTime();
		String                            F_KJQJ = billDataSet.getRowSet(0).getString(PO.GetValueByParamName(SYS_MODEL._BLFL_KJQJ_COL_, SYS_MDL_VAL.BILL_KJQJ), "");
		String                            F_GUID = billDataSet.getRowSet(0).getString(PO.GetValueByParamName(SYS_MODEL._BILL_GUID_COL_, SYS_MDL_VAL.BILL_GUID), "");
		String                            F_DJBH = billDataSet.getRowSet(0).getString(PO.GetValueByParamName(SYS_MODEL._BILL_BH_COL_, SYS_MDL_VAL.BILL_BH), null);
		String                             OP_ID = PO.GetValueByParamName("OP_ID", "");
		String                           FLOW_ID = "";
		String                     NODE_TAG_NAME = "";
		String                          NODE_TAG = "";
		java.util.List<String>    dataSetKeyList = new java.util.ArrayList<String>();
		
		nextFlowNodeRowSet = getNextFlowNodeRowSet(stmt, PO);
		preFlowNodeRowSet = getPreFlowNodeRowSet(stmt, PO, nextFlowNodeRowSet.getString("NODE_ID", ""));
		
		//查询全部部门审批的流程记录,取最新的代办任务
		strSql = " select max(OP_ID) as OP_ID, OP_BMBH from FLOW_TASK_LIST where FLOW_ID = '" + PO.GetValueByParamName(FLOW_TASK_LIST._FLOW_ID, "") + "' and BIZ_DATE = '" + F_KJQJ + "' and "
        	   + " BIZ_GUID = '" + F_GUID + "' and BIZ_DJBH ='" + F_DJBH + "' and NODE_TAG = '" + PO.GetValueByParamName(FLOW_TASK_LIST._OP_NODE, "") 
        	   + "' and RESR_STATUS = 'processed' and RESR_IN_CAUSE = 'waiting' and RESR_OUT_CAUSE = 'submit' GROUP BY OP_BMBH";
		rs = stmt.executeQuery(strSql);
		flowDataset = DataSetUtils.resultSet2DataSet(rs, flowDataset);
		
		//部门已经确认的信息
		strSql = " select * from FLOW_TASK_LIST where FLOW_ID = '" + PO.GetValueByParamName(FLOW_TASK_LIST._FLOW_ID, "") + "' and BIZ_DATE = '" + F_KJQJ + "' and "
		 	   + " BIZ_GUID = '" + F_GUID + "' and BIZ_DJBH ='" + F_DJBH + "' "
		 	   + " and TASK_STATUS = 'ending' order by (OP_ID + 0) desc";
		rs = stmt.executeQuery(strSql);
		endFlowDataset = DataSetUtils.resultSet2DataSet(rs, endFlowDataset);
		
		for(int i = flowDataset.getRowCount() - 1; i >= 0; i--) {
			if(endFlowDataset.getRowSet(flowDataset.getRowSet(i).getString("OP_BMBH", "")) != null) {
				flowDataset.removeRowSet(i);
			}
		}
		
		//待部门确认
		strSql = " select * from FLOW_TASK_LIST where FLOW_ID = '" + PO.GetValueByParamName(FLOW_TASK_LIST._FLOW_ID, "") + "' and BIZ_DATE = '" + F_KJQJ + "' and "
	 	       + " BIZ_GUID = '" + F_GUID + "' and BIZ_DJBH ='" + F_DJBH + "' "
	 	       + " and NODE_SRC = 'N3' and NODE_TAG = 'N4' and RESR_STATUS = 'pending' order by (OP_ID + 0) desc";
		rs = stmt.executeQuery(strSql);
		QRFlowDataset = DataSetUtils.resultSet2DataSet(rs, QRFlowDataset);
		for(int i = flowDataset.getRowCount() - 1; i >= 0; i--) {
			if(QRFlowDataset.getRowSet(flowDataset.getRowSet(i).getString("OP_BMBH", "")) != null) {
				flowDataset.removeRowSet(i);
			}
		}
		
		//查询部门
		strSql = " select F_BMBH, F_BMMC from HYBMZD where F_SYZT = '1'";
		rs = stmt.executeQuery(strSql);
		BMDataset = DataSetUtils.resultSet2DataSet(rs, BMDataset);
		
		//如果不是结束节点，则需要更新上一个流程节点任务信息，同时还要插入一条新的记录
		strSql = "select * from FLOW_TASK_LIST where FLOW_ID = '" + PO.GetValueByParamName(FLOW_TASK_LIST._FLOW_ID, "") + "' and BIZ_DATE = '" + F_KJQJ + "' and "
        	   + " BIZ_GUID = '" + F_GUID + "' and BIZ_DJBH ='" + F_DJBH + "' and NODE_TAG = '" + PO.GetValueByParamName(FLOW_TASK_LIST._OP_NODE, "") 
        	   + "' and OP_ID = '" + OP_ID + "' order by (OP_ID + 0) desc";
		
		rs = stmt.executeQuery(strSql);
		
		if(rs != null && rs.next()) {
			FLOW_ID = rs.getString("FLOW_ID");
			//更新上一个任务节点的状态
			strSql = "update FLOW_TASK_LIST set RESR_STATUS = 'processed', RESR_OUT_CAUSE = '" + PO.GetValueByParamName(FLOW_TASK_LIST._RESR_OUT_CAUSE, "submit") + "'"
				   + " where OP_ID = '" + OP_ID + "' and FLOW_ID = '" + FLOW_ID + "'";
			stmt.execute(strSql);
			
			//获取提交到节点名称
			strSql = "select * from FLOW_NODE_LIST where FLOW_ID ='" + FLOW_ID + "' and NODE_NEXT = '" + nextFlowNodeRowSet.getString("NODE_ID", "") + "'";
			rs = stmt.executeQuery(strSql);
			if(rs != null && rs.next()) {
				NODE_TAG = rs.getString("NODE_ID");
				NODE_TAG_NAME = rs.getString("NODE_NAME");
			}
			curTime = new Date().getTime();
			if(billDataSet.getRowCount() > 0) {
				itemRowSet = billDataSet.getRowSet(0);
				dataSetKeyList = itemRowSet.getDataSetKeyList();
				if(dataSetKeyList.size() > 0) {
					itemDataSet = itemRowSet.getDataSet(dataSetKeyList.get(0));

					//如果部门已全部审批，则进入下一个节点
					for(int i = 0; i < itemDataSet.getRowCount(); i++) {
						//如果退回说明为空，则说明不需要退回,但是需要更新之前等待的任务记录为pending
						if(flowDataset.getRowSet(itemDataSet.getRowSet(i).getString("F_BMBH", "")) == null) continue;
						//如果退回说明不为空，则说明需要退回，需要插入一条代办任务给退回部门，让他重新审批
						curTime++;
						BMRowSet = (EFRowSet) BMDataset.getRowSet(itemDataSet.getRowSet(i).getString("F_BMBH", ""));	
						strSql = "insert into FLOW_TASK_LIST (OP_ID,FLOW_ID,BIZ_DJBH,BIZ_DATE,BIZ_GUID,OP_USER,OP_USER_NAME,OP_TIME,"
							   + "OP_BMBH,OP_NOTE,TASK_STATUS,OP_NODE,NODE_SRC,NODE_SRC_NAME,NODE_TAG,NODE_TAG_NAME,POP_ID,RESR_STATUS,TASK_TO_UNIT,TASK_TO_UNIT_NAME," ;
					    for(int j = 1; j <= 20; j++) {
					    	if(PO.GetValueByParamName(FLOW_TASK_LIST._F_CHAR + "0" + j, null) != null) {
					    		if(j < 10) {
						   			strSql += "F_CHAR0" + j + ",";
						   		} else {
						   			strSql += "F_CHAR" + j + ",";
						   		}
					    	}
					    	if(PO.GetValueByParamName(FLOW_TASK_LIST._F_DATE + "0" + j, null) != null) {
					    		if(j < 10) {
						   			strSql += "F_DATE0" + j + ",";
						   		} else {
						   			strSql += "F_DATE" + j + ",";
						   		}
					    	}
					    	if(PO.GetValueByParamName(FLOW_TASK_LIST._F_NUM + "0" + j, null) != null) {
					    		if(j < 10) {
						   			strSql += "F_NUM0" + j + ",";
						   		} else {
						   			strSql += "F_NUM" + j + ",";
						   		}
					    	}
					    }
				    	strSql += "RESR_IN_CAUSE,RESR_OUT_CAUSE) values ('"
				    	        + curTime + "', '" + PO.GetValueByParamName(FLOW_TASK_LIST._FLOW_ID, "") + "', '"
							    + F_DJBH + "', '" + F_KJQJ + "', '" + F_GUID + "', '" + PO.GetValueByParamName(FLOW_TASK_LIST._OP_USER, "")
							    + "', '" + PO.GetValueByParamName(FLOW_TASK_LIST._OP_USER_NAME, "") + "', '"
							    + curTime + "', '" + PO.GetValueByParamName(FLOW_TASK_LIST._OP_BMBH, "") + "', '" 
							    + PO.GetValueByParamName(FLOW_TASK_LIST._OP_NOTE, "") + "', 'processing', '"
							    + PO.GetValueByParamName(FLOW_TASK_LIST._OP_NODE, "") + "', '" + PO.GetValueByParamName(FLOW_TASK_LIST._OP_NODE, "") + "', '"
							    + PO.GetValueByParamName(FLOW_TASK_LIST._NODE_SRC_NAME, "") + "', '" + NODE_TAG + "', '" + NODE_TAG_NAME 
							    + "', '" + OP_ID + "', '" + PO.GetValueByParamName(FLOW_TASK_LIST._RESR_STATUS, "") 
							    + "','" + BMRowSet.getString("F_BMBH", "") + "', '" + BMRowSet.getString("F_BMMC", "") + "',";
				    	for(int j = 1; j <= 20; j++) {
				    		if(PO.GetValueByParamName(FLOW_TASK_LIST._F_CHAR + "0" + j, null) != null) {
				    			if(j < 10) {
					    			strSql += "'" + PO.GetValueByParamName(FLOW_TASK_LIST._F_CHAR + "0" + j, null)  + "',";
					    		} else {
					    			strSql += "'" + PO.GetValueByParamName(FLOW_TASK_LIST._F_CHAR + j, null) + "',";
					    		}
				    		}
				    		if(PO.GetValueByParamName(FLOW_TASK_LIST._F_DATE + "0" + j, null) != null) {
				    			if(j < 10) {
					    			strSql += "'" + PO.GetValueByParamName(FLOW_TASK_LIST._F_DATE + "0" + j, null)  + "',";
					    		} else {
					    			strSql += "'" + PO.GetValueByParamName(FLOW_TASK_LIST._F_DATE + j, null) + "',";
					    		}
				    		}
				    		if(PO.GetValueByParamName(FLOW_TASK_LIST._F_NUM + "0" + j, null) != null) {
				    			if(j < 10) {
					    			strSql += "'" + PO.GetValueByParamName(FLOW_TASK_LIST._F_NUM + "0" + j, null)  + "',";
					    		} else {
					    			strSql += "'" + PO.GetValueByParamName(FLOW_TASK_LIST._F_NUM + j, null) + "',";
					    		}
				    		}				    		
				    	}
					    strSql += "'" + PO.GetValueByParamName(FLOW_TASK_LIST._RESR_IN_CAUSE, "") + "', '')";
						stmt.execute(strSql);
					}
					itemDataSet.setPrimeKey(new String[]{"F_BMBH"});
					itemDataSet.buildPrimeKeyIndex();
					for(int i = 0; i < flowDataset.getRowCount(); i++) {
						//如果退回说明为空，则说明不需要退回,但是需要更新之前等待的任务记录为pending
						if(itemDataSet.getRowSet(flowDataset.getRowSet(i).getString("OP_BMBH", "")) == null) {
							flowRowSet = (EFRowSet) flowDataset.getRowSet(i);
							strSql = " update FLOW_TASK_LIST set RESR_OUT_CAUSE = '', RESR_STATUS = 'pending' where OP_ID = '" + flowRowSet.getString("OP_ID", "") + "'";
							stmt.execute(strSql);
							continue;
						}
					}
				}
			}	
		}
	}
	
	//获取流程信息
	private EFRowSet getFlowRowSet(Statement stmt, JParamObject PO) throws Exception {
		String OP_ID = PO.GetValueByParamName("OP_ID", "");
		ResultSet rs = null;
		EFRowSet flowRowSet = EFRowSet.getInstance();
		String strSql = "select * from FLOW_TASK_LIST where OP_ID = '" + OP_ID + "'";
		rs = stmt.executeQuery(strSql);
		if(rs != null && rs.next()) {
			flowRowSet = (EFRowSet) DataSetUtils.resultSet2RowSet(rs, flowRowSet);
		}
		return flowRowSet;
	}
	
	//获取下一个节点信息
	private EFRowSet getNextFlowNodeRowSet(Statement stmt, JParamObject PO) throws Exception {
		ResultSet              rs = null;
		EFRowSet   flowNodeRowSet = EFRowSet.getInstance();;
		String             strSql = " select FLOW_NODE_LIST.NODE_ID,FLOW_NODE_LIST.NODE_NAME,FLOW_NODE_LIST.FLOW_ID,FLOW_NODE_LIST.NODE_RETRIEVE,"
			                      + " FLOW_NODE_LIST.NODE_TYPE,FLOW_NODE_LIST.NODE_NEXT,FLOW_NODE_LIST.NODE_STATUS,FLOW_NODE_NEXT_LIST.NODE_NAME as NODE_NEXT_NAME"
			                      + " from FLOW_NODE_LIST "
			                      + " LEFT JOIN FLOW_NODE_LIST FLOW_NODE_NEXT_LIST ON FLOW_NODE_LIST.FLOW_ID = FLOW_NODE_NEXT_LIST.FLOW_ID "
			                      + " where FLOW_NODE_LIST.NODE_NEXT = FLOW_NODE_NEXT_LIST.NODE_ID and "
                                  + " exists(SELECT 1 FROM FLOW_USER_LIST where FLOW_USER_LIST.FLOW_BH = FLOW_NODE_LIST.FLOW_ID and ((FLOW_USER_LIST.FLOW_BM = '"
                                  + PO.GetValueByParamName("OP_BMBH", "")
                                  + "' and FLOW_USER_LIST.F_TYPE = 'BM')or (FLOW_USER_LIST.FLOW_USER = '"
                                  + PO.GetValueByParamName("OP_USER", "")
                                  + "' and FLOW_USER_LIST.FLOW_BM = '" + PO.GetValueByParamName("OP_BMBH", "") + "' and FLOW_USER_LIST.F_TYPE = 'USER'))"
                                  + " and FLOW_USER_LIST.NODE_BH = FLOW_NODE_LIST.NODE_ID)";
		if(PO.GetValueByParamName("NODE_TYPE", "").trim().length() > 0) {
			strSql += " and FLOW_NODE_LIST.NODE_TYPE = '" + PO.GetValueByParamName("NODE_TYPE", "") + "'";
		}
		if(PO.GetValueByParamName("NODE_ID", "").trim().length() > 0) {
			strSql += " and FLOW_NODE_LIST.NODE_ID = '" + PO.GetValueByParamName("NODE_ID", "") + "'";
		}
		strSql += " and FLOW_NODE_LIST.FLOW_ID = '" + PO.GetValueByParamName(FLOW_TASK_LIST._FLOW_ID, "") + "'";
		rs = stmt.executeQuery(strSql);
		if(rs != null && rs.next()) {
			flowNodeRowSet = (EFRowSet) DataSetUtils.resultSet2RowSet(rs, flowNodeRowSet);
		}
		return flowNodeRowSet;
	}
	
	//获取上一个节点信息
	private EFRowSet getPreFlowNodeRowSet(Statement stmt, JParamObject PO, String NODE_ID) throws Exception {
		ResultSet              rs = null;
		EFRowSet   flowNodeRowSet = EFRowSet.getInstance();;
		String             strSql = " select *"
			                      + " from FLOW_NODE_LIST "
			                      + " where FLOW_NODE_LIST.NODE_NEXT = '"
                                  + NODE_ID + "' ";
		strSql += " and FLOW_NODE_LIST.FLOW_ID = '" + PO.GetValueByParamName(FLOW_TASK_LIST._FLOW_ID, "") + "'";
		rs = stmt.executeQuery(strSql);
		if(rs != null && rs.next()) {
			flowNodeRowSet = (EFRowSet) DataSetUtils.resultSet2RowSet(rs, flowNodeRowSet);
		}
		return flowNodeRowSet;
	}
}
